<template>
  <div class="audit-detail-container">
    <div class="header">
      <div class="header-content d-flex justify-content-between align-items-center">
        <h2>
          {{ isLegalSpecialist ? '法务审核 - 合同详情' : '财务审核 - 合同详情' }}
        </h2>
        <div>
          <!-- 返回按钮（美化） -->
          <button @click="goBack" class="btn btn-back mr-2">
            <i class="fa fa-arrow-left mr-2"></i>返回
          </button>
          <!-- 完成审核按钮（美化） -->
          <button v-if="isAllClausesApproved" @click="completeAudit" class="btn btn-complete">
            <i class="fa fa-check mr-2"></i>完成审核
          </button>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-indicator">
      <div class="spinner"></div>
      <p>加载中...</p>
    </div>

    <!-- 错误消息 -->
    <div v-if="errorMessage" class="error-message">
      <i class="fa fa-exclamation-circle mr-2"></i>{{ errorMessage }}
    </div>

    <!-- 合同基本信息 -->
    <div v-if="!loading && contract" class="card mt-4">
      <div class="card-header bg-info text-white">
        <h3>合同基本信息</h3>
      </div>
      <div class="card-body">
        <div class="row">
          <div class="col-md-6">
            <p><strong>合同ID:</strong> {{ contract.id }}</p>
            <p><strong>合同名称:</strong> {{ contract.name }}</p>
            <p><strong>项目经理:</strong> {{ contract.projectManagerName }}</p>
            <p><strong>客户公司:</strong> {{ contract.customerCompanyName }}</p>
            <p><strong>创建时间:</strong> {{ formatDate(contract.createTime) }}</p>
          </div>
          <div class="col-md-6">
            <p><strong>合同状态:</strong> {{ contractStatusText }}</p>
            <p><strong>客户联系人:</strong> {{ contract.customerContactName }}</p>
            <p><strong>客户电话:</strong> {{ contract.customerContactInfo }}</p>
            <p><strong>最后更新时间:</strong> {{ formatDate(contract.updateTime) }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 合同条款列表 -->
    <div v-if="!loading && clauses.length > 0" class="card mt-4">
      <div class="card-header bg-secondary text-white">
        <h3>合同条款 (共 {{ totalClauses }} 条)</h3>
      </div>
      <div class="card-body">
        <div class="clauses-table overflow-x-auto">
          <table class="table table-bordered-custom table-hover">
            <thead class="bg-light">
            <tr>
              <th>条款ID</th>
              <th>条款内容</th>
              <th>审核状态</th>
              <th>操作</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="clause in clauses" :key="clause.id">
              <td>{{ clause.id }}</td>
              <td style="max-width: 300px; word-break: break-all;">{{ clause.content }}</td>
              <td>
                <span :class="getStatusClass(clause.auditStatus)">{{ clause.auditStatusDisplayName }}</span>
              </td>
              <td>
                <!-- 审核按钮（美化） -->
                <button
                    v-if="clause.auditStatus === 'PENDING'"
                    @click="auditClause(route.params.contractId, clause.id)"
                    class="btn btn-audit"
                >
                  <i class="fa fa-edit mr-2"></i>审核
                </button>
                <!-- 已审核按钮（美化） -->
                <button
                    v-else
                    class="btn btn-disabled"
                    disabled
                >
                  <i class="fa fa-lock mr-2"></i>已审核
                </button>
              </td>
            </tr>
            </tbody>
          </table>
        </div>

        <!-- 分页控件（按钮美化） -->
        <div class="pagination mt-3 d-flex justify-content-between">
          <div>
            显示第 {{ currentClausePage + 1 }} 页，共 {{ totalClausePages }} 页
          </div>
          <div class="pagination-buttons">
            <button
                @click="prevClausePage"
                :disabled="currentClausePage === 0 || loading"
                class="btn btn-page"
            >
              <i class="fa fa-chevron-left"></i> 上一页
            </button>
            <button
                @click="nextClausePage"
                :disabled="currentClausePage === totalClausePages - 1 || loading"
                class="btn btn-page"
            >
              下一页 <i class="fa fa-chevron-right"></i>
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 没有条款 -->
    <div v-else-if="!loading && clauses.length === 0" class="card mt-4">
      <div class="card-body">
        <div class="empty-message text-center py-4">
          <i class="fa fa-info-circle text-info display-4 mb-3"></i>
          <h4>合同中没有条款</h4>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { ref, onMounted, watch, computed } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'

export default {
  name: 'AuditContractDetail',
  setup() {
    const store = useStore()
    const router = useRouter()
    const route = useRoute()

    const contractId = ref(null)
    const loading = ref(true)
    const errorMessage = ref('')
    const contract = ref(null)
    const clauses = ref([])
    const currentClausePage = ref(0)
    const pageSize = ref(10)
    const totalClausePages = ref(0)
    const totalClauses = ref(0)

    // 用户信息
    const employeeId = ref(null)
    const employeePosition = ref(null)
    const isLegalSpecialist = ref(false)
    const isFinanceSpecialist = ref(false)

    // 返回上一页
    const goBack = () => {
      router.push('/employee/audit-contracts')
    }

    // 获取合同详情
    const fetchContract = () => {
      loading.value = true
      errorMessage.value = ''

      // 从路由参数获取合同ID
      const contractIdFromRoute = route.params.contractId
      if (!contractIdFromRoute || !employeeId.value) {
        errorMessage.value = '数据加载中，请稍后...'
        loading.value = false
        return
      }

      // 使用路由参数中的合同ID
      contractId.value = contractIdFromRoute

      // 确定审核类型
      const auditType = isLegalSpecialist.value ? 'legal' : 'finance'

      // 获取合同详情（添加分页参数）
      axios.get(`/auth/contracts/${contractId.value}/audit`, {
        headers: {
          'X-Employee-Id': employeeId.value,
          'X-Employee-Position': employeePosition.value
        },
        params: {
          type: auditType,
          page: currentClausePage.value,
          size: pageSize.value
        }
      })
          .then(response => {
            contract.value = response.data.contract
            clauses.value = response.data.clauses || []
            totalClausePages.value = response.data.totalClausePages || 1
            totalClauses.value = response.data.totalClauses || 0
          })
          .catch(error => {
            console.error('获取合同详情失败', error)
            errorMessage.value = error.response?.status === 403
                ? '您没有权限审核此合同'
                : '获取合同详情失败，请稍后再试'
          })
          .finally(() => {
            loading.value = false
          })
    }

    // 审核条款
    const auditClause = (contractId, clauseId) => {
      // 构造完整跳转链接
      const url = `/employee/audit-clause/${contractId}/${clauseId}`
      router.push(url)
    }

    // 完成合同审核
    const completeAudit = () => {
      if (!confirm('确定要完成合同审核吗？所有条款必须已审核')) {
        return
      }

      // 完成审核逻辑
      axios.put(`/auth/contracts/${contract.value.id}/complete-audit`, null, {
        headers: {
          'X-Employee-Id': employeeId.value,
          'X-Employee-Position': employeePosition.value
        }
      })
          .then(() => {
            alert('合同审核已完成')
            router.push('/employee/audit-contracts')
          })
          .catch(err => {
            console.error('完成审核失败', err)
            alert('完成审核失败，请重试')
          })
    }

    // 分页操作
    const prevClausePage = () => {
      if (currentClausePage.value > 0 && !loading.value) {
        currentClausePage.value--
        fetchContract()
      }
    }

    const nextClausePage = () => {
      if (currentClausePage.value < totalClausePages.value - 1 && !loading.value) {
        currentClausePage.value++
        fetchContract()
      }
    }

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString()
    }

    // 计算属性：合同状态文本
    const contractStatusText = computed(() => {
      if (!contract.value) return '未知'
      switch (contract.value.status) {
        case 'DRAFT': return '草稿'
        case 'PENDING_REVIEW': return '待审核'
        case 'PENDING_AUDIT': return '审核中'
        case 'APPROVED': return '已批准'
        case 'REJECTED': return '已拒绝'
        case 'COMPLETED': return '已完成'
        default: return contract.value.status
      }
    })

    // 计算属性：所有条款是否已审核
    const isAllClausesApproved = computed(() => {
      if (!clauses.value) return true
      return clauses.value.every(clause => clause.auditStatus !== 'PENDING')
    })

    // 获取状态样式
    const getStatusClass = (status) => {
      switch (status) {
        case 'PENDING': return 'badge bg-warning'
        case 'APPROVED': return 'badge bg-success'
        case 'REJECTED': return 'badge bg-danger'
        default: return 'badge bg-secondary'
      }
    }

    onMounted(() => {
      // 初始化用户信息
      employeeId.value = store.state.user?.id
      employeePosition.value = store.state.user?.position
      isLegalSpecialist.value = store.state.user?.position === 'LEGAL_SPECIALIST'
      isFinanceSpecialist.value = store.state.user?.position === 'FINANCE_SPECIALIST'

      // 监听用户信息变化
      watch([
        () => store.state.user?.id,
        () => store.state.user?.position
      ], () => {
        employeeId.value = store.state.user?.id
        employeePosition.value = store.state.user?.position
        isLegalSpecialist.value = store.state.user?.position === 'LEGAL_SPECIALIST'
        isFinanceSpecialist.value = store.state.user?.position === 'FINANCE_SPECIALIST'
        fetchContract()
      })

      fetchContract()
    })

    return {
      loading,
      errorMessage,
      contract,
      clauses,
      currentClausePage,
      pageSize,
      totalClausePages,
      totalClauses,
      goBack,
      auditClause,
      completeAudit,
      prevClausePage,
      nextClausePage,
      formatDate,
      contractStatusText,
      isAllClausesApproved,
      getStatusClass,
      isLegalSpecialist,
      isFinanceSpecialist,
      route
    }
  }
}
</script>

<style scoped>
.audit-detail-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  background-color: #f8f9fa;
  padding: 15px 20px;
  border-radius: 6px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.header-content {
  width: 100%;
}

/* 基础按钮样式 */
.btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  transition: all 0.2s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.btn i {
  font-size: 14px;
}

/* 按钮交互反馈 */
.btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.btn:active:not(:disabled) {
  transform: translateY(0);
  box-shadow: 0 2px 3px rgba(0, 0, 0, 0.1);
}

.btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

/* 按钮分类样式 */
/* 1. 返回按钮 */
.btn-back {
  background-color: #6c757d;
  color: #fff;
}

.btn-back:hover:not(:disabled) {
  background-color: #5a6268;
}

/* 2. 完成审核按钮 */
.btn-complete {
  background-color: #28a745;
  color: #fff;
}

.btn-complete:hover:not(:disabled) {
  background-color: #218838;
}

/* 3. 审核按钮 */
.btn-audit {
  background-color: #007bff;
  color: #fff;
}

.btn-audit:hover:not(:disabled) {
  background-color: #0069d9;
}

/* 4. 已审核（禁用）按钮 */
.btn-disabled {
  background-color: #6c757d;
  color: #fff;
  opacity: 0.7;
}

/* 5. 分页按钮 */
.btn-page {
  background-color: #f8f9fa;
  color: #495057;
  border: 1px solid #dee2e6;
  padding: 4px 10px;
}

.btn-page:hover:not(:disabled) {
  background-color: #e9ecef;
}

/* 加载状态 */
.loading-indicator {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  min-height: 300px;
}

.spinner {
  width: 50px;
  height: 50px;
  border: 3px solid rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  border-top-color: #007bff;
  animation: spin 1s ease-in-out infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

/* 错误消息 */
.error-message {
  color: #dc3545;
  background-color: #f8d7da;
  padding: 12px 15px;
  border-radius: 4px;
  margin: 20px 0;
  display: flex;
  align-items: center;
  border-left: 3px solid #dc3545;
}

/* 卡片样式 */
.card {
  border: none;
  border-radius: 6px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.06);
  overflow: hidden;
  margin-bottom: 20px;
}

.card-header {
  padding: 12px 20px;
  font-weight: 600;
  font-size: 16px;
}

.card-body {
  padding: 20px;
}

/* 表格样式 */
.table {
  width: 100%;
  margin-bottom: 0;
  border-collapse: separate;
  border-spacing: 0;
}

.table th,
.table td {
  padding: 12px 15px;
  vertical-align: middle;
  text-align: left;
}

.table th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #495057;
  border-bottom: 2px solid #e9ecef;
}

.table tr {
  transition: background-color 0.2s;
}

.table tr:hover {
  background-color: #f8fafc;
}

.table-bordered-custom {
  border-collapse: separate;
  border-spacing: 0;
  width: 100%;
}

.table-bordered-custom thead th,
.table-bordered-custom tbody td {
  border: none;
  border-right: 1px solid #dee2e6;
  border-bottom: 1px solid #dee2e6;
}

.table-bordered-custom thead th:last-child,
.table-bordered-custom tbody td:last-child {
  border-right: none;
}

.table-bordered-custom thead th {
  border-top: 1px solid #dee2e6;
}

/* 状态徽章样式 */
.badge {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 0.85em;
  font-weight: 500;
  color: #fff;
}

.bg-warning { background-color: #ffc107; }
.bg-success { background-color: #28a745; }
.bg-danger { background-color: #dc3545; }
.bg-secondary { background-color: #6c757d; }

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.pagination-buttons {
  display: flex;
  gap: 8px;
}

/* 空状态样式 */
.empty-message {
  text-align: center;
  padding: 40px 20px;
  background-color: #f8fafc;
  border-radius: 6px;
  border: 1px dashed #e2e8f0;
}

.empty-message i {
  color: #94a3b8;
  margin-bottom: 15px;
}

.empty-message h4 {
  color: #1e293b;
  margin-bottom: 8px;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }

  .btn {
    width: 100%;
    justify-content: center;
  }

  .pagination {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }

  .pagination-buttons {
    width: 100%;
    justify-content: space-between;
  }
}
</style>